package com.firewolf.struts.fileupload.actions;

import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.firewolf.struts.fileupload.models.User;
import com.firewolf.struts.fileupload.service.UserService;

public class DownLoadAction extends Action {

	@Override
	public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request,
			HttpServletResponse response) throws Exception {
	
		//get请求参数过滤器不生效，转码获取真实名称
		String userName = new String(request.getParameter("user").getBytes("ISO-8859-1"),"utf-8");
		
		User user = new UserService().getUserByName(userName);
		String fileName = getServlet().getServletContext().getRealPath("/files")+"\\"+user.getNewPhoto();
		//设置请求头，告诉浏览器是一个附件
		//注意要把文件名称进行编码，否则会乱码导致文件下载不了
		response.addHeader("Content-dispostion", "attachment;fileName="+URLEncoder.encode(user.getOrignPhoto(), "utf-8"));
		InputStream is = null;
		OutputStream os = null;
		try{
			is = new FileInputStream(fileName);
			os = response.getOutputStream();
			int len = 0;
			byte[] buf = new byte[1024];
			while((len = is.read(buf))>0)
				os.write(buf,0,len);
		}catch(Exception e){
			e.printStackTrace();
		}finally{
			os.close();
			is.close();
		}
		
		return mapping.findForward("show");
	}

	
	
}
